import React, { Component, Fragment } from 'react';
import { Spin, Row, Col, Card, Form, Input, message, Button, Tooltip, Icon, Select, Checkbox,Tag } from 'antd';
import { connect } from 'dva';
//import HeaderTab from '@/components/HeaderTab';
import router from 'umi/router';
// import MultiCrops from 'react-multi-crops';
import MultiCrops from '@/components/multiCrops';
import SelectedImage from '@/components/plugins/selectImage/index';

const { CheckableTag } = Tag;
const FormItem = Form.Item;
const Option = Select.Option;
import styles from './newexpress.less';

@Form.create()
class newexpress extends Component {

    state={
        tabs: [
            {
              title: '快速发货',
              key: `/${window.storeId}/delivery/express`,
              // disabled: true
            },
            {
              title: '快递单模板',
              key: `/${window.storeId}/delivery/expressbilltemplate/add`,
            },
          ],   
          coordinates: [
              // {
              //   height: 63,
              //   id: "w9paDyOH6",
              //   width: 132,
              //   x: 100,
              //   y: 80,
              // }
          ], 
          selectedList:[],  
          fontWeightTagChecked:false,
          fontStyleTagChecked:false,
          fontSpace:0,
          fontSize:12,
          selectedIndex:-1,
          selectedCoordinate:{} ,
          loaded:false       
    }

    componentDidMount(){
        window.Isoption = true;
        const { dispatch,match } = this.props;
        dispatch({
            type:'deliverManage/GetStoreExpressList', 
            callback:{
                success:()=>{
                    if(!match.params.id){
                        this.setState({
                            loaded:true
                        })
                    }
                }
            }          
        })
        if(match.params.id){
            this.getInfo(match.params.id)
        }
    }

    componentWillMount() {
        window.Isoption = false;
      }


    // 根据id获取模板信息
    getInfo = (id) => {
        const { dispatch,form:{setFieldsValue} } = this.props;       
        dispatch({
            type:'expressBill/GetInfo', 
            param:{
                Id:id
            },
            callback:{
                success:(data)=>{                    
                    setFieldsValue({
                        ExpressId:data.Data.ExpressId,
                        //ExpressName:data.Data.ExpressName,
                        TempLateName:data.Data.TempLateName,
                        TemplateWidth:data.Data.TemplateWidth,
                        TemplateHeight:data.Data.TemplateHeight,
                        BackGround:data.Data.BackGround,
                    })
                    if(data.Data.JsonData&&typeof data.Data.JsonData === 'string'){
                        let jsonData=JSON.parse(data.Data.JsonData);
                        this.setState({
                            selectedList:jsonData.selectedList,
                            // fontSize:jsonData.fontSize,
                            // fontSpace:jsonData.fontSpace,
                            coordinates:jsonData.coordinates,
                        })
                    }
                    this.setState({
                        loaded:true
                    })
                }
            }          
        })
    }

    addInput = (e,text) => {
        const { coordinates,selectedList } = this.state;        
        let checked=e.target.checked;
        let value=e.target.value;      
        if(checked){
            coordinates.push({
                height: 63,
                id: value,
                width: 132,
                x: 0,
                y: 0,
                text:text,
                fontSize:12,
                fontSpace:0,
                fontWeightTagChecked:false,
                fontStyleTagChecked:false
            })
            selectedList.push(value)
        }else{
            let index=coordinates.findIndex(item=>item.id==value);
            index>-1?coordinates.splice(index,1):''; 
            index>-1?selectedList.splice(index,1):'';         
        }

        this.setState({
            coordinates,
            selectedList
        })
    }
    
    //
    changeCoordinate = (coordinate, index, coordinates) => {   

        this.setState({
            coordinates,
            selectedCoordinate:coordinate
        })
    }
    deleteCoordinate = (coordinate, index, coordinates) => {
        const { selectedList } = this.state; 
        let arr=JSON.parse(JSON.stringify(coordinates));         
        arr.forEach(item=>{
            item.selectedIndex=-1;
        })   
        selectedList.splice(index,1);  
        this.setState({
            coordinates:arr,
            selectedList,
            selectedIndex:-1,
            selectedCoordinate:{}
        },()=>{
            this.forceUpdate()
        })
    }

     // 头部标签页切换
    onTabChange = id => {
        this.setState(
        {
            activeId: id,
        },
        () => {
            if(id===`/${window.storeId}/delivery/expressbilltemplate/add`){
                router.replace({
                    pathname: `/${window.storeId}/delivery/expressbilltemplate/list`,
                });
            }else{
                router.replace({
                    pathname: `${id}`,
                });
            }              
        }
        );
    };

    imgModal = ref => {
        this.imgmodal = ref;
    };  

    OpenImageModal = () => {
        this.imgmodal.handleShowModal();
    };

    onImageChange = res => {
        const { form:{setFieldsValue}} = this.props;
        console.log(res)
        setFieldsValue({
            BackGround:res.imageUrl
        })
        this.imgmodal.handleModalVisible();
    };

    // 选择物流公司
    changeExpress = (val) => {
        const { form:{setFieldsValue} } = this.props; 
        let BackGroundImg= `xkdnewyun/systemfile/ship/${val==63?'ship_sf':val==67?'ship_ems':val==150?'ship_zhongtong':val==81?'ship_shentong':''}.jpg?x-oss-process=style/1080`;              
        setFieldsValue({                    
            BackGround:BackGroundImg,
        })
        
    }

    // 保存
    save = () => {
        const { form , dispatch,match} = this.props;
        const { coordinates ,selectedList,fontSize,fontSpace} = this.state;
        form.validateFields((err,values)=>{
            if(err) return;
            if(!selectedList.length) return message.error('至少要勾选一个打印项');
            let obj={};
            obj.selectedList=selectedList;
            // obj.fontSize=fontSize;
            // obj.fontSpace=fontSpace;
            obj.coordinates=coordinates;
            if(match.params.id){
                dispatch({
                    type:'expressBill/EditPrintTpl',
                    param:{
                        Id:match.params.id,
                        ExpressId:values.ExpressId,
                        TempLateName:values.TempLateName,
                        TemplateWidth:values.TemplateWidth,
                        TemplateHeight:values.TemplateHeight,
                        BackGround:values.BackGround,
                        JsonData:JSON.stringify(obj)
                    },
                    callback:{
                        success:()=>{
                            message.success("保存成功")
                            this.cancel()
                        },
                        error:(data)=>{
                            message.error(data.Msg)
                        }
                    }
                })
            }else{
                dispatch({
                    type:'expressBill/AddPrintTpl',
                    param:{
                        ExpressId:values.ExpressId,
                        TempLateName:values.TempLateName,
                        TemplateWidth:values.TemplateWidth,
                        TemplateHeight:values.TemplateHeight,
                        BackGround:values.BackGround,
                        JsonData:JSON.stringify(obj)
                    },
                    callback:{
                        success:()=>{
                            message.success("保存成功")
                            this.cancel()
                        },
                        error:(data)=>{
                            message.error(data.Msg)
                        }
                    }
                })
            }
        })
    }

    // 取消
    cancel = () => {
        router.replace({
            pathname: `/${window.storeId}/delivery/expressbilltemplate/list`,
          });
    }

    // 字体加粗、斜体
    handleTagChange = (type,checked) => {
        const { coordinates,selectedCoordinate,selectedIndex } = this.state;
        if(selectedIndex<0) return;
        let obj=JSON.parse(JSON.stringify(selectedCoordinate));        
        let arr=JSON.parse(JSON.stringify(coordinates));
        arr.forEach(item=>{
            item.selectedIndex=selectedIndex;
        }) 
        obj=arr[selectedIndex];
        if(type==1){           
            arr[selectedIndex].fontWeightTagChecked=checked;
            obj.fontWeightTagChecked=checked;
        }else{           
            arr[selectedIndex].fontStyleTagChecked=checked;
            obj.fontStyleTagChecked=checked;
        }
        this.setState({          
            selectedCoordinate:obj,
            coordinates:arr,
        },()=>{
            this.translate({target:{value:arr[selectedIndex].x}},1)
        })       
    }  
    
    // 字体大小、间距
    fontChange = (e,type) => {
        const { coordinates,selectedCoordinate,selectedIndex } = this.state;
        if(selectedIndex<0) return;
        let obj=JSON.parse(JSON.stringify(selectedCoordinate));        
        let arr=JSON.parse(JSON.stringify(coordinates));
        arr.forEach(item=>{
            item.selectedIndex=selectedIndex;
        }) 
        obj=arr[selectedIndex];
        if(type==1){
            arr[selectedIndex].fontSize=e;
            obj.fontSize=e;           
        }else{
            arr[selectedIndex].fontSpace=e;
            obj.fontSpace=e;           
        }
        this.setState({          
             selectedCoordinate:obj,
             coordinates:arr,
         },()=>{
            this.translate({target:{value:arr[selectedIndex].x}},1)
         })
    }

    // 选择的文本域
    onSelect = (index) => {
        const { coordinates,selectedCoordinate } = this.state;       
        let obj=JSON.parse(JSON.stringify(selectedCoordinate));
        obj=coordinates[index];
        this.setState({
            selectedIndex:index,
            selectedCoordinate:obj,           
        },()=>{
            this.translate({target:{value:coordinates[index].x}},1)
        })       
    }

    // 偏移量 
    translate = (e,type) => {        
        let val=e.target.value-0;
        const { coordinates,selectedCoordinate,selectedIndex } = this.state;       
        if(selectedIndex<0) return;
        let obj=JSON.parse(JSON.stringify(coordinates));  
        obj.forEach(item=>{
            item.selectedIndex=selectedIndex;
        })      
        if(type==1){
            if(val+obj[selectedIndex].width>840) return;
            selectedCoordinate.x=val-0;
            obj[selectedIndex].x=val-0;
        }else{
            if(val+obj[selectedIndex].height>450) return;
            selectedCoordinate.y=val-0;
            obj[selectedIndex].y=val-0;
        }       
        this.setState({
            coordinates:obj,
            selectedCoordinate,
        },()=>{
            this.forceUpdate();            
        })      
    }

    // 校验
    validate = (rule,value,callback) => {
        if(value){
            if(Number(value)<=0||Number(value)>500){
                callback('只能填写1~500的正整数')
            }else{
                let reg = /^\d+$/g;               
                if(!reg.test(value)){
                    callback('只能填写1~500的正整数')
                }else{
                    callback()
                }
            }
        }else{
            callback('此项为必填项')
        }
    }

    validateName = (rule,value,callback) => {
        let val=value?value.replace(/(^\s*)|(\s*$)/g, ""):undefined;
        if(!val){
            callback('此项为必填项')
        }else{
            callback()
        }
    }


    render() {
        const { coordinates,selectedList ,selectedCoordinate,selectedIndex,loaded} = this.state;
        const { 
            expressList,
            form:{getFieldDecorator,getFieldValue},
            submitLoading,
            submitLoading2,
            loading,
            cdnUrl
        } = this.props;      
        const formItemLayout = {
            labelCol: {
                xs: { span: 8 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 16 },
                sm: { span: 16 },
            },
        };  
        let BackGroundImg= `http://insidexkd.oss-cn-shanghai.aliyuncs.com/xkdnewyun/systemfile/ship/${getFieldValue("ExpressId")==63?'ship_sf':getFieldValue("ExpressId")==67?'ship_ems':getFieldValue("ExpressId")==150?'ship_zhongtong':getFieldValue("ExpressId")==81?'ship_shentong':''}.jpg?x-oss-process=style/1080`;      
        return (
            <Fragment>                
                <Spin spinning={!loaded}>
                    <Card
                        bordered={false}
                        title="基本信息"
                        className={styles.NewExpressHead}
                    >
                        <Form layout="inline">
                            <Row>
                                <Col span={8}>
                                    <FormItem
                                        required
                                        label="物流公司"
                                        {...formItemLayout}
                                    >
                                        {
                                            getFieldDecorator('ExpressId',{  
                                             validateTrigger:'onBlur',                                             
                                                rules:[
                                                    {required:true,message:'此项为必选项'}
                                                ]
                                            })(
                                                <Select  className="xkd-width-per-100" style={{width:'100%'}} onChange={this.changeExpress}>
                                                    {
                                                        expressList.map(item=>{
                                                            return <Option value={item.Id} key={item.Id}>{item.Name}</Option>
                                                        })
                                                    }                                            
                                                </Select>
                                            )
                                        }                                        
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem
                                        required
                                        label="快递单长度"
                                        {...formItemLayout}
                                    >                                        
                                        {
                                            getFieldDecorator('TemplateWidth',{
                                                validateTrigger:'onBlur',
                                                rules:[                                                
                                                    {validator: this.validate},                                                  
                                                ]
                                            })(
                                                <Input addonAfter="mm" />
                                            )
                                        } 
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem
                                        required
                                        label="快递单宽度"
                                        {...formItemLayout}
                                    >                                        
                                        {
                                            getFieldDecorator('TemplateHeight',{
                                                validateTrigger:'onBlur',
                                                rules:[                                                  
                                                    {validator: this.validate},
                                                ]
                                            })(
                                                <Input addonAfter="mm" />
                                            )
                                        } 
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={8}>
                                    <FormItem
                                        required
                                        label="模板名称"
                                        {...formItemLayout}
                                    >                                        
                                        {
                                            getFieldDecorator('TempLateName',{
                                                validateTrigger:'onBlur',
                                                rules:[
                                                    //{required:true,message:'此项为必填项'}
                                                     {validator: this.validateName},
                                                ]
                                            })(
                                                <Input placeholder="" style={{ width: '100%' }} maxLength={20}/>
                                            )
                                        } 
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem
                                       // required
                                        label="上传底图"
                                        {...formItemLayout}
                                    >                                                                               
                                        {
                                            getFieldDecorator('BackGround')(
                                                <Button className="xkd-mr8" onClick={this.OpenImageModal}>上传底图</Button>
                                            )
                                        } 
                                            <Tooltip
                                            placement="right"
                                            title="底图的尺寸建议跟填写的快递单长宽尺寸保持一致，大小不超过3M"
                                            overlayClassName="NewExpressTip"
                                        >
                                            <Icon type="info-circle" />
                                        </Tooltip>
                                    </FormItem>
                                </Col>

                            </Row>

                        </Form>
                    </Card>
                    <Card
                        bordered={false}
                        title="打印项"
                        className={styles.NewExpressOption}
                    >
                        <Row className="OptionTitle">
                            <Col span={6}>发件人信息</Col>
                            <Col span={6}>收件人信息</Col>
                            <Col span={6}>商品订单信息</Col>
                            <Col span={6}>其他信息</Col>
                        </Row>
                        <Checkbox.Group style={{ width: '100%' }} value={selectedList}>
                        <Row className="OptionInfo">
                            <Col span={6}>
                                
                                    <Row>
                                        <Col span={12}><Checkbox value={1} onChange={(e)=>this.addInput(e,'发件人-姓名')}>发件人-姓名</Checkbox></Col>
                                        <Col span={12}><Checkbox value={2} onChange={(e)=>this.addInput(e,'发件人-地址')}>发件人-地址</Checkbox></Col>
                                        <Col span={12}><Checkbox value={3} onChange={(e)=>this.addInput(e,'发件人-电话')}>发件人-电话</Checkbox></Col>
                                    </Row>
                                
                            </Col>
                            <Col span={6}>
                                
                                    <Row>
                                        <Col span={12}><Checkbox value={4} onChange={(e)=>this.addInput(e,'收件人-姓名')}>收件人-姓名</Checkbox></Col>
                                        <Col span={12}><Checkbox value={5} onChange={(e)=>this.addInput(e,'收件人-电话')}>收件人-电话</Checkbox></Col>
                                        <Col span={12}><Checkbox value={6} onChange={(e)=>this.addInput(e,'收件人-邮编')}>收件人-邮编</Checkbox></Col>
                                        <Col span={12}><Checkbox value={7} onChange={(e)=>this.addInput(e,'收件人-地址')}>收件人-地址</Checkbox></Col>
                                        <Col span={14}><Checkbox value={8} onChange={(e)=>this.addInput(e,'收件人-目的地')}>收件人-目的地</Checkbox></Col>
                                    </Row>
                                
                            </Col>
                            <Col span={6}>
                                
                                    <Row>
                                        <Col span={12}><Checkbox value={9} onChange={(e)=>this.addInput(e,'订单编号')}>订单编号</Checkbox></Col>
                                        <Col span={12}><Checkbox value={10} onChange={(e)=>this.addInput(e,'商品列表')}>商品列表</Checkbox></Col>
                                        <Col span={12}><Checkbox value={11} onChange={(e)=>this.addInput(e,'买家备注')}>买家备注</Checkbox></Col>
                                        <Col span={12}><Checkbox value={12} onChange={(e)=>this.addInput(e,'商家备注')}>商家备注</Checkbox></Col>
                                    </Row>
                                
                            </Col>
                            <Col span={6}>                                
                                    <Row>
                                        <Col span={12}><Checkbox value={13} onChange={(e)=>this.addInput(e,'店铺名称')}>店铺名称</Checkbox></Col>
                                        <Col span={12}><Checkbox value={14} onChange={(e)=>this.addInput(e,'打印日期')}>打印日期</Checkbox></Col>
                                    </Row>                               
                            </Col>
                        </Row>
                        </Checkbox.Group>
                        <div className="xkd-mt16">
                                    <Row 
                                        className="OptionTitle" 
                                       // style={{borderBottomWidth:getFieldValue("ExpressId")?0:'1px'}} 
                                       style={{borderBottomWidth:0}}                                      
                                    >
                                        <Col span={12} style={{borderRight:0}}>
                                            <Row gutter={8}>
                                                <Col span={10}>
                                                    <Row>
                                                        <Col span={8} style={{width:'5em'}}>
                                                            <span style={{lineHeight:'32px'}}>文字大小：</span>                                                            
                                                        </Col>
                                                        <Col span={16}>                                                            
                                                            <Select value={selectedCoordinate.fontSize}  style={{ width: '100%' }} onChange={(e)=>this.fontChange(e,1)}>
                                                                <Option value={10}>10px</Option>
                                                                <Option value={12}>12px</Option>                                               
                                                                <Option value={14}>14px</Option>                                                
                                                                <Option value={16}>16px</Option>
                                                                <Option value={18}>18px</Option>
                                                                <Option value={20}>20px</Option>
                                                                <Option value={22}>22px</Option>
                                                                <Option value={24}>24px</Option>
                                                                <Option value={48}>48px</Option>
                                                            </Select>
                                                        </Col>
                                                    </Row>
                                                </Col>
                                                <Col span={10}>                                                    
                                                    <Row>
                                                        <Col span={8} style={{width:'5em'}}>
                                                            <span style={{lineHeight:'32px'}}>文字间距：</span>                                                            
                                                        </Col>
                                                        <Col span={16}>                                                            
                                                            <Select value={selectedCoordinate.fontSpace}  style={{ width: "100%" }} onChange={(e)=>this.fontChange(e,2)}>
                                                                <Option value={0}>0px</Option>
                                                                <Option value={2}>2px</Option>                                               
                                                                <Option value={4}>4px</Option>                                                
                                                                <Option value={6}>6px</Option>
                                                                <Option value={8}>8px</Option>
                                                                <Option value={10}>10px</Option>
                                                                <Option value={12}>12px</Option>
                                                                <Option value={14}>14px</Option>
                                                                <Option value={20}>20px</Option>
                                                            </Select>
                                                        </Col>
                                                    </Row>
                                                </Col>
                                                <Col span={4} style={{lineHeight:'32px'}}>
                                                    <CheckableTag checked={selectedCoordinate.fontWeightTagChecked} onChange={(checked)=>this.handleTagChange(1,checked)} style={{fontSize:16,fontStyle:'italic'}}>B</CheckableTag>
                                                    <CheckableTag checked={selectedCoordinate.fontStyleTagChecked} onChange={(checked)=>this.handleTagChange(2,checked)} style={{fontSize:16,fontStyle:'italic'}}>I</CheckableTag>
                                                </Col>
                                            </Row>                                                                                        
                                        </Col>
                                        <Col span={12}>
                                            <Row style={{textAlign:'right'}} gutter={8}>                                                 
                                                <Col span={10} className="xkd-fr">
                                                    <Row>
                                                        <Col span={8} style={{width:'5em'}}>
                                                            <span style={{lineHeight:'32px'}}>纵向偏移：</span>                                                           
                                                        </Col>
                                                        <Col span={16}>                                                            
                                                            <Input 
                                                                addonAfter="px" 
                                                                style={{width:'100%'}} 
                                                                value={selectedCoordinate.y}
                                                                onChange={(val)=>this.translate(val,2)}
                                                            />
                                                        </Col>
                                                    </Row>
                                                </Col>    
                                                <Col span={10} className="xkd-fr">                                                                                                        
                                                    <Row>
                                                        <Col span={8} style={{width:'5em'}}>
                                                            <span style={{lineHeight:'32px'}}>横向偏移：</span>                                                          
                                                        </Col>
                                                        <Col span={16}>                                                            
                                                            <Input 
                                                                addonAfter="px" 
                                                                style={{width:'100%'}} 
                                                                value={selectedCoordinate.x}
                                                                 onChange={(val)=>this.translate(val,1)}
                                                            />
                                                        </Col>
                                                    </Row>
                                                </Col>                                            
                                            </Row>
                                        </Col>                                        
                                    </Row>
                                </div>
                                <Row className="Edit">
                                        <Col>                                
                                            <div style={{textAlign:'center',width:840,minHeight:450,margin:'0 auto',position:'relative'}}>
                                                <MultiCrops
                                                    src={getFieldValue("BackGround")?cdnUrl+'/'+getFieldValue("BackGround"):getFieldValue("ExpressId")?BackGroundImg:''}
                                                    // width={840}
                                                    // height={450}
                                                    maxWidth={'100%'}
                                                    selectedIndex={selectedIndex}
                                                    coordinates={coordinates}
                                                    onChange={this.changeCoordinate}
                                                    onDelete={this.deleteCoordinate}
                                                    onSelect={this.onSelect}                                      
                                                >                                        
                                                </MultiCrops>                               
                                            </div>
                                        </Col>
                                    </Row>
                    </Card>
                    <div className="xkd-bottom-actions">                                                                        
                        <Button
                            onClick={this.cancel}
                        // loading={draftLoading}
                            //disabled={id === 0 ? false : type === 1 ? loading1 : loading2}                            
                        >
                            取消
                        </Button>
                        <Button
                            type="primary"
                            onClick={this.save}
                            loading={submitLoading||submitLoading2}
                            disabled={loading}
                            className="xkd-ml8"
                        >
                            保存
                        </Button>
                    </div>
                </Spin>
                <SelectedImage onRef={this.imgModal}    selectImage={this.onImageChange} allUrl={false}/>
            </Fragment>
        );
    }
}
export default connect(({ deliverManage, global, loading }) => ({ 
    cdnUrl:global.oemInfo.cdnUrl,
    expressList:deliverManage.expressList,  
    loading:loading.effects['expressBill/GetInfo'],  
    submitLoading: loading.effects['expressBill/AddPrintTpl'],  
    submitLoading2: loading.effects['expressBill/EditPrintTpl'],  
    allLoading:loading.global
  }))(newexpress);
